package com.lsy.weizhi2.activity;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lsy.weizhi2.JsonObject.MyCollectNote;
import com.lsy.weizhi2.JsonObject.NoteList;
import com.lsy.weizhi2.JsonObject.ReplyList;
import com.lsy.weizhi2.JsonObject.YueDanSuccess;
import com.lsy.weizhi2.R;
import com.lsy.weizhi2.adapter.NoteDetailAdapter;
import com.lsy.weizhi2.config.Constants;
import com.lsy.weizhi2.config.MyHeight;
import com.lsy.weizhi2.customview.ReplyDailog;
import com.lsy.weizhi2.mybase.MyBaseActivity;
import com.lsy.weizhi2.mybase.MyTitleView;
import com.lsy.weizhi2.myutils.DaShangPopupCall;
import com.lsy.weizhi2.myutils.DetailAdapterCall;
import com.lsy.weizhi2.myutils.ManagerItem;
import com.lsy.weizhi2.myutils.NoteDetailUPCall;
import com.lsy.weizhi2.myutils.ReplyDailogCall;
import com.lsy.weizhi2.popupwindow.DaShangPopup;
import com.lsy.weizhi2.utils.MyMethod;
import com.lsy.weizhi2.utils.MyOkHttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NoteDetail extends MyBaseActivity implements View.OnClickListener {
    private Context context;
    private MyTitleView note_detail;
    private RecyclerView note_detail_rv;
    private NoteDetailAdapter noteDetailAdapter;
    private LinearLayout note_detail_bottom_ll;
    private ImageView note_detail_collection, note_detail_mobile;
    private TextView note_detail_yuyue, note_detail_baoming;
    private int xx;
    private DaShangPopup daShangPopup;
    private PopupWindow mPopupWindow;
    private RelativeLayout note_detail_view, gengduo_rl;
    private ReplyDailog reply_dialog;
    private Handler handler = new Handler(Looper.getMainLooper());
    private int pageNo = 1;

    private String json,tag;//传进来的帖子
    private NoteList.ListBean notebean;
    private MyCollectNote.ListBean listBean;
    private int orderId,avatar;
    private Gson gson;
    private ReplyList replyList;
    private List<ReplyList.ListBean> list_r;
    public static int CreateId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_note_detail);
        context = NoteDetail.this;
        gson = new Gson();
        json = getIntent().getStringExtra("json");
        tag = getIntent().getStringExtra("tag");
        Log.i("NoteDetail","json==="+json);
        if(tag!=null&&tag.equals(""+ ManagerItem.CollectWeiZhi)){
            listBean = gson.fromJson(json,MyCollectNote.ListBean.class);
            orderId=listBean.getOrder().getId();
            CreateId=listBean.getOrder().getCreateUserId();
            avatar=listBean.getOrder().getAvatar();
        }else{
            notebean = gson.fromJson(json, NoteList.ListBean.class);
            orderId=notebean.getId();
            CreateId=notebean.getCreateUserId();
            avatar=notebean.getAvatar();
        }
        NoteClick(orderId);
        Init();
    }

    @Override
    protected void onStart() {
        super.onStart();
        noteDetailAdapter.setDetailAdapterCall(new DetailAdapterCall() {
            @Override
            public void UPClick(View view, int flag) {
                switch (flag){
                    case NoteDetailUPCall.REPORT:
                        ShowJuBao(context,avatar,DaShangPopupCall.JuBao,0);
                        break;
                }
            }

            @Override
            public void Receive() {
                pageNo=1;
                getReplyList();
            }

            @Override
            public void JuBaoOrPingBi(int flag, int position) {
                switch (flag){
                    case DetailAdapterCall.PingBi://屏蔽
                        int orderReplyId=list_r.get(position-1).getId();
                        PingBi(orderReplyId);
                        break;
                    case DetailAdapterCall.JuBao://举报
                        ShowJuBao(context,avatar,DaShangPopupCall.JuBao,list_r.get(position-1).getId());
                        break;
                }
            }
        });
    }

    public void ShowYuyue(Context context,int avatar,int flag){
        daShangPopup.yuyue(context,note_detail_view,avatar,flag,0);
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 0.5f;
        getWindow().setAttributes(params);
    }

    public void ShowJuBao(Context context,int avatar,int flag,int orderReplyId){
        daShangPopup.yuyue(context,note_detail_view,avatar,flag,orderReplyId);
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 0.5f;
        getWindow().setAttributes(params);
    }

    public void ShowPopup(String title, String tv_1, String tv_2) {
        daShangPopup.init(context, note_detail_view, title, tv_1, tv_2, DaShangPopupCall.DASHANG);
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 0.5f;
        getWindow().setAttributes(params);
    }

    public void ShowPhone(String phone,String msg) {
        daShangPopup.connect(context, note_detail_view, DaShangPopupCall.CONNECT, phone,msg);
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 0.5f;
        getWindow().setAttributes(params);
    }

    public void ShowInvite(String title, String liuyan, String tv_2, String btn) {
        daShangPopup.invite(context, note_detail_view, DaShangPopupCall.INVITE, title, liuyan, tv_2, btn);
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 0.5f;
        getWindow().setAttributes(params);
    }
    boolean bottom;
    @Override
    protected void onResume() {
        super.onResume();
        xx = 0;
        ViewTreeObserver vto = note_detail.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (xx < 1) {
                    xx++;
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(note_detail.getLayoutParams());
                            params.height = MyHeight.ACTIONBAR + MyHeight.MyTitleHeight;
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                                note_detail.setLayoutParams(params);
                            }
                        }
                    });
                }
            }
        });

        note_detail_rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                boolean islast = note_detail_rv.canScrollVertically(1);
                if (newState == RecyclerView.SCROLL_STATE_DRAGGING && !islast) {
                    if (list_r.size() == (pageNo) * 10) {
                        noteDetailAdapter.UpData(list_r, true, 2);
                    } else {
                        noteDetailAdapter.UpData(list_r, true, 3);
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                noteDetailAdapter.UpData(list_r, false, 0);
                            }
                        }, 1000);
                    }
                    bottom=true;
                } else if(bottom&&newState==RecyclerView.SCROLL_STATE_IDLE&&!islast){
                    if (list_r.size() == (pageNo) * 10) {
                        noteDetailAdapter.UpData(list_r, true, 1);
                        pageNo++;
                        getReplyList();
                    } else {
                        noteDetailAdapter.UpData(list_r, true, 3);
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                noteDetailAdapter.UpData(list_r, false, 0);
                            }
                        }, 1000);
                    }
                    bottom=false;
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });

        daShangPopup.setDaShangPopupCall(new DaShangPopupCall() {
            @Override
            public void dismissListener() {
                WindowManager.LayoutParams params = getWindow().getAttributes();
                params.alpha = 1.0f;
                getWindow().setAttributes(params);
            }

            @Override
            public void connect(View view, int flag) {
                switch (flag) {
                    case DaShangPopupCall.DASHANG:
                        MyMethod.showToast(context, "打赏" + daShangPopup.getPrice() + "微币");
                        break;
                    case DaShangPopupCall.INVITE:
                        //MyMethod.showToast(context, "打赏" + daShangPopup.getPrice() + "微币");
                        //Invite();
                        break;
                    case DaShangPopupCall.CONNECT:
                        String btn=daShangPopup.getBtn();
                        if(btn.equals("一键拨号")){
                            MyMethod.CallPhone(context,daShangPopup.getPhone());
                        }else if(btn.equals("私信联系")){
                            int friendId;
                            if(tag!=null&&tag.equals(""+ManagerItem.CollectWeiZhi)){
                                friendId=listBean.getCreateUserId();
                            }else{
                                friendId=notebean.getCreateUserId();
                            }
                            MyMethod.toActivity(context,MySelfMessage2.class,new String[]{"friendId"},new String[]{friendId+""});
                            daShangPopup.dismiss();
                        }

                       /* Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + daShangPopup.getPhone()));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                            // TODO: Consider calling
                            //    ActivityCompat#requestPermissions
                            // here to request the missing permissions, and then overriding
                            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                            //                                          int[] grantResults)
                            // to handle the case where the user grants the permission. See the documentation
                            // for ActivityCompat#requestPermissions for more details.
                            return;
                        }
                        startActivity(intent);*/
                        break;
                }
            }

            @Override
            public void yuyue(String str) {
                Invite(str);
            }

            @Override
            public void jubao(String msg,int orderReplyId) {
                if(orderReplyId!=0){
                    JuBao(msg,orderReplyId);
                }else{
                    JuBao2(msg);
                }

            }
        });
        pageNo=1;
        getReplyList();
    }

    /**
     * 立即预约
     */
    private void Invite(String str){
        Map<String,String>map=new HashMap<>();
            map.put("orderId",orderId+"");
        if(str!=null&&str.length()!=0){
            map.put("message",str);
        }
        MyOkHttpUtils.getInstance(context).doPost(Constants.YueDan,map)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        if(message!=null){
                            try {
                                JSONObject jsonObject=new JSONObject(message);
                                boolean result=jsonObject.getBoolean("result");
                                if(result){
                                    YueDanSuccess yueDanSuccess=gson.fromJson(message,YueDanSuccess.class);
                                    MyMethod.showToast(context,"预约成功");
                                    YueDanSuccess.DataBean dataBean=yueDanSuccess.getData();
                                    String msg=dataBean.getMessage();
                                    if(msg!=null){
                                        SendMsg(dataBean.getUserId(),msg);
                                    }
                                    Log.i("NoteDetail","下单成功");
                                    finish();
                                }else{
                                    Log.i("NoteDetail","下单失败");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                    }
                });
    }

    /**
     * 预约成功后发送私信
     */
    private void SendMsg(int friendId,String msg){
        Map<String,String> map=new HashMap<>();
        map.put("friendId",friendId+"");
        map.put("messageContent",msg);
        MyOkHttpUtils.getInstance(context).doPost(Constants.SendPrivateMessage,map)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        if(message!=null){
                            try {
                                JSONObject jsonObject=new JSONObject(message);
                                boolean result = jsonObject.getBoolean("result");
                                if(result){

                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }


    /**
     * 分页获取回复
     */
    private void getReplyList() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNo", pageNo+"");
        map.put("pageSize", "10");
        MyOkHttpUtils.getInstance(context).doGet(Constants.SELECT_ORDER_REPLY + orderId + "/reply", map)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        Log.i("NoteDetail", "message====111111===" + message);
                        replyList = gson.fromJson(message, ReplyList.class);
                        if (pageNo == 1) {
                            list_r.clear();
                            Log.i("NoteDetail", "clear");
                        }
                        List<ReplyList.ListBean> list = replyList.getList();
                        if (list != null && list.size() != 0) {
                            list_r.addAll(list);
                            noteDetailAdapter.UpData(list_r, false, 0);
                        } else {
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    noteDetailAdapter.UpData(list_r,false,0);
                                }
                            },1000);
                        }
                    }
                });
    }

    @Override
    public void onPause() {
        super.onPause();
        xx = 0;
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    private void Init() {
        daShangPopup = new DaShangPopup();
        list_r = new ArrayList<>();
        note_detail_view = (RelativeLayout) findViewById(R.id.note_detail_view);
        gengduo_rl = (RelativeLayout) findViewById(R.id.gengduo_rl);
        note_detail = (MyTitleView) findViewById(R.id.note_detail);
        note_detail_rv = (RecyclerView) findViewById(R.id.note_detail_rv);
        note_detail_bottom_ll = (LinearLayout) findViewById(R.id.note_detail_bottom_ll);
        note_detail_collection = (ImageView) findViewById(R.id.note_detail_collection);
        note_detail_mobile = (ImageView) findViewById(R.id.note_detail_mobile);
        note_detail_yuyue = (TextView) findViewById(R.id.note_detail_yuyue);
        reply_dialog = (ReplyDailog) findViewById(R.id.reply_dialog);
        LinearLayoutManager manager = new LinearLayoutManager(context);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        note_detail_rv.setLayoutManager(manager);
        if(tag!=null&&tag.equals(""+ManagerItem.CollectWeiZhi)){
            noteDetailAdapter = new NoteDetailAdapter(context, listBean);
        }else{
            noteDetailAdapter = new NoteDetailAdapter(context, notebean);
        }
        note_detail_rv.setAdapter(noteDetailAdapter);
        note_detail_collection.setOnClickListener(this);
        note_detail_mobile.setOnClickListener(this);
        note_detail_yuyue.setOnClickListener(this);
        gengduo_rl.setOnClickListener(this);
        note_detail.setTitle("微职详情");
        reply_dialog.setReplyDailogCall(new ReplyDailogCall() {
            @Override
            public void onClick(View view, int flag) {
                switch (flag) {
                    case ReplyDailogCall.CANCEL://点击取消关闭对话框
                        reply_dialog.setVisibility(View.GONE);
                        break;
                    case ReplyDailogCall.OK:
                        //点击确定发送消息并关闭对话框
                        String reply_info = reply_dialog.getText();
                        ReceiveOrder(orderId + "", reply_info);
                        reply_dialog.setVisibility(View.GONE);
                        break;
                }
            }
        });
    }

    /**
     * 回复帖子
     * @param order_id
     * @param content
     */
    private void ReceiveOrder(String order_id, String content) {
        Map<String, String> map = new HashMap<>();
        map.put("orderId", order_id);
        map.put("content", content);
        MyOkHttpUtils.getInstance(context).doPost(Constants.RECEIVE_NOTE, map)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        Log.i("NoteDetail", "message=receive=" + message);
                        pageNo=1;
                        getReplyList();
                    }
                });
    }

    /**
     * 主界面点击事件
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.note_detail_collection://点击了收藏
                ShouCang();
                break;
            case R.id.note_detail_mobile:
                //调用接口根据结果返回提示
                TellPhone();

                /*if (phone % 2 == 1) {
                    ShowPhone();
                } else {
                    ShowInvite("小主，您需要打赏1万微币才可以联系我", null, "已经打赏9900微币，还差100微币", "慷慨打赏");
                }
                phone++;*/
                break;
            case R.id.note_detail_yuyue://立即预约
                ShowYuyue(context,avatar,DaShangPopupCall.YUYUE);
               // Invite();
                /**
                 * 此处为付款弹框
                 */
                //ShowInvite("小主，您需要打赏1万微币才可以联系我", "留言：一起去唱歌，有时间吗么？", "已经打赏9900微币，还差100微币", "立即预约");
                break;
            case R.id.gengduo_rl:
                reply_dialog.setVisibility(View.VISIBLE);
                break;
        }
    }

    /**
     * 联系他
     */
    private void TellPhone(){
        MyOkHttpUtils.getInstance(context).doGet(Constants.GetPhone+orderId+"/phone",null)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        if(message!=null){
                            try {
                                JSONObject jsonObject=new JSONObject(message);
                                boolean result = jsonObject.getBoolean("result");
                                if(result){
                                    String phone = jsonObject.getString("data");
                                    ShowPhone(phone,null);
                                }else{
                                    String msg = jsonObject.getString("message");
                                    ShowPhone(null,msg);
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    /**
     * 收藏帖子
     */
    private void ShouCang() {
        MyOkHttpUtils.getInstance(context).doPost(Constants.ShouCang + "/" + orderId, null)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        if (message != null) {
                            try {
                                JSONObject jsonObject = new JSONObject(message);
                                boolean result = jsonObject.getBoolean("result");
                                if (result) {
                                    MyMethod.showToast(context, "收藏成功");
                                } else {
                                    MyMethod.showToast(context, jsonObject.getString("message"));
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                    }
                });
    }

    /**
     * 屏蔽评论
     */
    private void PingBi(int orderReplyId){
        MyOkHttpUtils.getInstance(context).doPut(Constants.PingBi+orderId+"/reply/"+orderReplyId+"/block",null)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {
                        MyMethod.showToast(context,message);
                    }

                    @Override
                    public void onResponse(String message) {
                        if(message!=null){
                            try {
                                JSONObject jsonObject=new JSONObject(message);
                                boolean result=jsonObject.getBoolean("result");
                                if(result){
                                    MyMethod.ShowDialog(context,"屏蔽成功");
                                    pageNo=1;
                                    getReplyList();
                                }else{
                                    MyMethod.ShowDialog(context,jsonObject.getString("message"));
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    /**
     * 举报评论
     * @param msg                 内容
     * @param orderReplyId        评论id
     */
    private void JuBao(String msg,int orderReplyId){
        Map<String,String>map=new HashMap<>();
        map.put("remark",msg);
        MyOkHttpUtils.getInstance(context).doPut(Constants.JuBao+orderReplyId+"/report",map)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        if(message!=null){
                            try {
                                JSONObject jsonObject=new JSONObject(message);
                                boolean result=jsonObject.getBoolean("result");
                                if(result){
                                    MyMethod.ShowDialog(context,"举报评论成功");
                                    daShangPopup.dismiss();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    /**
     * 举报帖子
     * @param msg                 内容
     */
    private void JuBao2(String msg){
        Map<String,String>map=new HashMap<>();
        map.put("remark",msg);
        MyOkHttpUtils.getInstance(context).doPut(Constants.JuBao2+orderId+"/report",map)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        if(message!=null){
                            try {
                                JSONObject jsonObject=new JSONObject(message);
                                boolean result=jsonObject.getBoolean("result");
                                if(result){
                                    MyMethod.ShowDialog(context,"举报帖子成功");
                                    daShangPopup.dismiss();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    /**
     * 点击帖子--进入该Activity且执行OnCreate计数
     * @param orderId
     */
    private void NoteClick(int orderId) {
        MyOkHttpUtils.getInstance(context).doPut(Constants.NoteClick + orderId + "/click", null)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        if(message!=null){
                            try {
                                JSONObject jsonObject=new JSONObject(message);
                                boolean result = jsonObject.getBoolean("result");
                                if(result){

                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }
}
